package com.simple.mipc.handler;

import android.os.Messenger;
import android.util.Log;

import com.simple.mipc.annotation.Res;
import com.simple.mipc.entity.Worker;
import com.simple.mipc.utils.ClassUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class MessageClient implements InvocationHandler {

    private static final String TAG = MessageClient.class.getName();

    /**
     * 服务端Messenger对象
     */
    private Messenger messenger, handler;

    private Map<Method, Worker> worker;

    public MessageClient(Class<?> clazz, Messenger messenger, Messenger handler) {
        this.messenger = messenger;
        this.handler = handler;
        initWork(clazz);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Worker worker = this.worker.get(method);
        if (Objects.isNull(worker)) {
            throw new IllegalArgumentException("没有对应的代理实现");
        }
        assert worker != null;
        worker.work(messenger, handler, args);
        return null;
    }

    private void initWork(Class<?> clazz) {
        Method[] methods = ClassUtil.getMethods(clazz);
        worker = Arrays.stream(methods).filter(method -> {
            Res res = method.getDeclaredAnnotation(Res.class);
            if (Objects.isNull(res)) {
                Log.e(TAG, String.format("缺少必要的注解：%s", Res.class));
                return false;
            }
            return true;
        }).collect(Collectors.toMap(method -> method, Worker::new)); // 创建Worker
    }
}
